from users.models import Address
from rest_framework import serializers
from users.models import User
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings
from django.conf import settings
from goods.models import SKU


# serializers.ModelSerializer
# serializers.Serializer
# ModelSerializer中提供了数据入库的方法
class RegisterCreateUserSerializer(serializers.ModelSerializer):
    """
    1.获取前端提交的数据 username,password,password2,mobile,sms_code,allow
    2.对提交的数据进行校验
        2.1 单个字段验证
            手机号是否正确
            allow校验
        2.2 多个字段验证
            密码是否一致
            短信验证码
    3.保存入库
    """""
    # ModelSerializer是根据fields 自动生成字段的
    # 满足需求的字段有六个,但fields 列表中只提供了三个符合条件的字段,需要另外添加三个字段
    # required 必须的  既能实现 序列化 也能实现反序列化
    # write_only 只能写入,而且在反序列化的时候必须写入
    password2 = serializers.CharField(label='校验密码', allow_null=False, allow_blank=False, write_only=True)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6, allow_null=False, allow_blank=False,
                                     write_only=True)
    allow = serializers.CharField(label='是否同意协议', allow_null=False, allow_blank=False, write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)  # 增加token字段

    class Meta:
        model = User
        fields = ['id', 'username', 'password', 'mobile', 'password2', 'sms_code', 'allow', 'token']

        # 设定约束
        extra_kwargs = {
            'id': {'read_only': True},
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 2.对提交的数据进行校验
    # 2.1 单个字段验证
    # 手机号是否正确
    def validate_mobile(self, value):
        if not re.match(r'1[345789]\d{9}', value):
            raise serializers.ValidationError('手机号格式不正确')
        return value

    # allow校验
    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意协议')
        return True

    # 2.2 多个字段验证
    def validate(self, attrs):
        # 密码是否一致
        password = attrs.get('password')
        password2 = attrs.get('password2')
        if password != password2:
            raise serializers.ValidationError('密码不一致')

        # 短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        # 连接redis
        redis_conn = get_redis_connection('code')
        # 获取redis中保存的短信验证码
        redis_code = redis_conn.get('sms_%s' % mobile)
        # 判断短信验证码是否过期
        if not redis_code:
            raise serializers.ValidationError('短信验证码已过期')
        # 短信验证码是否一致
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')

        return attrs

    def create(self, validated_data):

        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        user = super().create(validated_data)

        # 密码加密
        user.set_password(validated_data['password'])
        user.save()

        # 需要在创建了用户之后,我们采用jwt给它生成一个token
        # 需要去获取两个方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        # 把token信息传递给user
        # 让我们在进行 序列化操作的时候把token返回给浏览器
        user.token = token

        return user


class UserCenterInfoSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailUpdateSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ['id', 'email']
        extra_kwargs = {
            'email': {
                'required': True
            }
        }

    # 序列化器中进行更新操作
    # 只更新邮件信息
    def update(self, instance, validated_data):

        email = validated_data.get('email')
        instance.email = email
        instance.save()

        # 发送邮件
        from django.core.mail import send_mail
        # # subject : 主题
        subject = '美多商城'
        # # message : 消息,普通内容
        message = ''
        # # from_email : 谁发送的
        from_email = settings.EMAIL_FROM
        # # recipient_list : 谁接收
        recipient_list = [email]
        # # html_message=None
        html_message = '<h1>lalala</h1>'

        # 生成一个对id和email,进行处理的url
        verify_url = instance.generice_active_url()

        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        # send_mail(subject, message, from_email, recipient_list, html_message=html_message)
        from celery_tasks.email.tasks import send_verify_email
        send_verify_email.delay(subject, message, from_email, recipient_list, html_message=html_message)

        return instance


class UserHistorySerializer(serializers.Serializer):
    sku_id = serializers.CharField(label='商品id', required=True)

    def validate_sku_id(self, value):

        # 判断商品是否存在
        try:
            SKU.objects.get(pk=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')

        return value

    #　在视图中调用了save方法,save方法需要重写,让数据保存在redis中
    def create(self, validated_data):
        # 记录用户记录的时候,key确保用户记录的唯一性
        # history_id
        user = self.context['request'].user
        sku_id = validated_data.get('sku_id')
        # 1.连接redis
        redis_conn = get_redis_connection('history')
        # 2.保存在列表中,先去重
        redis_conn.lrem('history_%s' % user.id, 0, sku_id)
        # 3.再添加数据
        redis_conn.lpush('history_%s' % user.id, sku_id)
        # 4.只保留五条数据(redis不能保存太多的数据)
        redis_conn.ltrim('history_%s' % user.id, 0, 4)

        return validated_data


class SKUSerializer(serializers.ModelSerializer):

    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'default_image_url', 'comments']


class AddressSerializer(serializers.ModelSerializer):

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def create(self, validated_data):
        # Address模型类中有user属性,将user对象添加到模型类的创建参数中
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """""
    class Meta:
        model = Address
        fields = ('title',)

